﻿using SCADAEditor.Component;
using SCADAEditor.Container;
using SCADAEditor.EventMan;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace SCADAEditor
{
    public partial class Form1 : Form
    {
        private EventManager _eventManager;
        private ComponentList _componentList;
        private PropertyGridBinder binder;
        private WinformTreeDatastruct _treeData = new WinformTreeDatastruct(); // 添加窗口树数据结构

        private ComponentBase _selectedComponent;  // 添加字段保存当前选中的组件

        private ProjectManager _projectManager;

        public Form1()
        {
            InitializeComponent();
           
            _componentList = new ComponentList();  // 必须先初始化

            _projectManager = new ProjectManager(_componentList, _treeData);

            InitializeComponentList();  // 然后才能填充组件列表
            _eventManager = new EventManager();
            InitializeComponentListView();
            // 绑定窗口树数据到TreeWinformList控件
            TreeWinformList.HideSelection = false;  // 添加这行代码，使失去焦点后仍显示选中状态
            // 绑定窗口树数据到TreeWinformList控件
            _treeData.BindToTreeView(TreeWinformList);

             // 默认选中第0项
            if (TreeWinformList.Nodes.Count > 0)
            {
                TreeWinformList.SelectedNode = TreeWinformList.Nodes[0];
            }
            binder=new PropertyGridBinder(propertyGrid1);

            InitializeEvents();
        }

        private void InitializeEvents()
        {
            // 预定义事件注册
        }

        /// <summary>
        /// 初始化组件列表视图
        /// </summary>
        private void InitializeComponentListView()
        {
            // 设置ListviewComponentList控件属性
            ListviewComponentList.View = View.List;
            ListviewComponentList.Dock = DockStyle.Fill;
            //ListviewComponentList.Width = 200;
            ListviewComponentList.MultiSelect = false;
            ListviewComponentList.AllowDrop = true;

            // 直接填充组件列表，不需要重新创建控件
            PopulateComponentList();
            SetupDragDrop();
        }

        private void InitializeComponentList()
        {
             // 注册各种组件原型
            _componentList.RegisterComponent(ComponentType.功能键, new ButtonComponent());
            _componentList.RegisterComponent(ComponentType.文字批注, new TextAnnotationComponent());
            _componentList.RegisterComponent(ComponentType.日期时间, new DateTimeComponent());
            _componentList.RegisterComponent(ComponentType.位状态指示灯, new StatusIndicatorComponent());

            // 可以继续注册其他组件...
        }

        /// <summary>
        /// 填充组件列表
        /// </summary>
        private void PopulateComponentList()
        {
            ListviewComponentList.Items.Clear();

            foreach (var componentType in _componentList.GetAvailableComponents())
            {
                var item = new ListViewItem(componentType.ToString())
                {
                    Tag = new ComponentListItemData
                    {
                        ComponentType = componentType,
                        DisplayName = componentType.ToString()
                    }
                };
                ListviewComponentList.Items.Add(item);
            }
        }

        /// <summary>
        /// 设置拖放功能
        /// </summary>
        
        private void SetupDragDrop()
        {
            ListviewComponentList.MouseMove += (s, e) =>
            {
                if (e.Button == MouseButtons.Left && ListviewComponentList.SelectedItems.Count > 0)
                {
                    var itemData = (ComponentListItemData)ListviewComponentList.SelectedItems[0].Tag;
                    ListviewComponentList.DoDragDrop(itemData, DragDropEffects.Copy);
                }
            };

            /// <summary>
            /// 拖放进入事件处理
            /// </summary>
            canvas.DragEnter += (s, e) =>
            {
                if (e.Data.GetDataPresent(typeof(ComponentListItemData)))
                {
                    e.Effect = DragDropEffects.Copy;
                }
            };

            /// <summary>
            /// 拖放事件处理
            /// </summary>
            canvas.DragDrop += (s, e) =>
            {
                  // 检查拖拽数据是否为组件列表项数据
                if (e.Data.GetDataPresent(typeof(ComponentListItemData)))
                {
                    // 获取拖拽的组件数据
                    var itemData = (ComponentListItemData)e.Data.GetData(typeof(ComponentListItemData));
                    // 创建新组件实例
                    var component = _componentList.CreateComponent(itemData.ComponentType);
                    // 设置组件位置为鼠标释放位置（转换为画布坐标系）
                    component.Position = canvas.PointToClient(new Point(e.X, e.Y));
                    // 将组件添加到画布显示
                    canvas.AddComponent(component);

                    // 检查当前是否有选中的窗口节点
                    if (TreeWinformList.SelectedNode != null)
                    {
                        var nodeText = TreeWinformList.SelectedNode.Text;
                        var colonIndex = nodeText.IndexOf('：');
                        // 从节点文本中提取窗口ID（冒号前的数字部分）
                        if (colonIndex > 0 && int.TryParse(nodeText.Substring(0, colonIndex), out int windowId))
                        {
                            // 将组件添加到当前窗口的数据结构中
                            _treeData.AddComponentToWindow(windowId, component);
                        }
                    }
                }
            };

            // 添加画布点击事件
            canvas.MouseClick += (s, e) =>
            {
               // 查找点击位置的组件
                _selectedComponent = canvas.Components.FirstOrDefault(c => 
                    new Rectangle(c.Position, c.Size).Contains(e.Location));
                    
                if (_selectedComponent != null)
                {
                    // 将组件属性绑定到propertyGrid1
                    binder.Bind(_selectedComponent);
                }
                else
                {
                    // 如果点击空白处，清除选中
                    binder.Clear();
                }
            };
        }

        private class ComponentListItemData
        {
            public ComponentType ComponentType { get; set; }
            public string DisplayName { get; set; }
        }

        private void TreeWinformList_AfterSelect(object sender, TreeViewEventArgs e)
        {
           
            // 按窗口ID把组件绑定到对应的窗口上，调用AddComponentToWindow方法即可
            // 从节点文本中提取窗口ID
            var nodeText = e.Node.Text;
            var colonIndex = nodeText.IndexOf('：');
            if (colonIndex > 0 && int.TryParse(nodeText.Substring(0, colonIndex), out int windowId))
            {
                // 绑定对象
                binder.Bind(_treeData.GetWindowNodeById(windowId));

                // 清空当前画布
                canvas.Components.Clear();

                // 获取该窗口的所有组件
                var components = _treeData.GetWindowComponents(windowId);

                // 将组件添加到画布
                foreach (var component in components)
                {
                    canvas.AddComponent(component);
                }

                // 刷新画布显示
                canvas.Invalidate();
            }
        }

        private void 属性ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void TreeWinformList_Click(object sender, EventArgs e)
        {
            if (TreeWinformList.SelectedNode != null)
            {
                var nodeText = TreeWinformList.SelectedNode.Text;
                var colonIndex = nodeText.IndexOf('：');
                if (colonIndex > 0 && int.TryParse(nodeText.Substring(0, colonIndex), out int windowId))
                {
                    // 绑定对象
                    binder.Bind(_treeData.GetWindowNodeById(windowId));
                }
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //运行
            //MessageBox.Show("运行");
            
             // 获取当前窗口的所有组件
            if (TreeWinformList.SelectedNode != null)
            {
                var nodeText = TreeWinformList.SelectedNode.Text;
                var colonIndex = nodeText.IndexOf('：');
                if (colonIndex > 0 && int.TryParse(nodeText.Substring(0, colonIndex), out int windowId))
                {
                    var components = _treeData.GetWindowComponents(windowId);
                    
                    // 创建并显示运行时窗口
                    var runtimeWindow = new RuntimeWindow(components);
                    runtimeWindow.Size = new Size(800, 600); // 可以根据需要设置窗口大小
                    runtimeWindow.Text = "运行时窗口 - " + TreeWinformList.SelectedNode.Text;
                    
                    this.Hide(); // 隐藏编辑器窗口
                    runtimeWindow.ShowDialog(); // 显示运行时窗口
                    this.Show(); // 恢复显示编辑器窗口
                }
            }
        }

        private void 保存项目ToolStripMenuItem_Click(object sender, EventArgs e)
        {
             using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "SCADA项目文件 (*.scadaproj)|*.scadaproj";
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    // 收集所有节点文本
                    var nodeTexts = new List<string>();
                    foreach (TreeNode node in TreeWinformList.Nodes)
                    {
                        nodeTexts.Add(node.Text);
                    }
                    
                    _projectManager.SaveProject(saveDialog.FileName, nodeTexts);
                    MessageBox.Show("项目保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            // using (var saveDialog = new SaveFileDialog())
            //     {
            //         saveDialog.Filter = "SCADA项目文件 (*.scadaproj)|*.scadaproj";
            //         if (saveDialog.ShowDialog() == DialogResult.OK)
            //         {
            //             var projectData = new ProjectData();
                        
            //             // 获取所有窗口数据
            //             foreach (TreeNode node in TreeWinformList.Nodes)
            //             {
            //                 var nodeText = node.Text;
            //                 var colonIndex = nodeText.IndexOf('：');
            //                 if (colonIndex > 0 && int.TryParse(nodeText.Substring(0, colonIndex), out int windowId))
            //                 {
            //                     var windowData = new WindowData
            //                     {
            //                         Id = windowId,
            //                         Name = nodeText.Substring(colonIndex + 1)
            //                     };
                                
            //                     // 获取窗口组件
            //                     var components = _treeData.GetWindowComponents(windowId);
            //                     foreach (var component in components)
            //                     {
            //                         windowData.Components.Add(new ComponentData
            //                         {
            //                             Type = _componentList.GetComponentType(component),  // 改为调用ComponentList的方法
            //                             Position = component.Position,
            //                             Properties = component.ToJson() // 需要组件实现ToJson方法
            //                         });
            //                     }
                                
            //                     projectData.Windows.Add(windowData);
            //                 }
            //             }
                        
            //             // 序列化为JSON并保存
            //             var json = Newtonsoft.Json.JsonConvert.SerializeObject(projectData, Newtonsoft.Json.Formatting.Indented);
            //             System.IO.File.WriteAllText(saveDialog.FileName, json);
                        
            //             MessageBox.Show("项目保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //         }
            //     }
        }

       

        private void 载入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var openDialog = new OpenFileDialog())
    {
        openDialog.Filter = "SCADA项目文件 (*.scadaproj)|*.scadaproj";
        if (openDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                 // 清空当前数据但不创建新实例
                TreeWinformList.Nodes.Clear();
                _treeData.Clear(); // 需要为WinformTreeDatastruct添加Clear方法
                canvas.Components.Clear();
                _projectManager.LoadProject(openDialog.FileName);
                _treeData.BindToTreeView(TreeWinformList);
                
                if (TreeWinformList.Nodes.Count > 0)
                {
                    TreeWinformList.SelectedNode = TreeWinformList.Nodes[0];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
            // using (var openDialog = new OpenFileDialog())
            // {
            //     openDialog.Filter = "SCADA项目文件 (*.scadaproj)|*.scadaproj";
            //     if (openDialog.ShowDialog() == DialogResult.OK)
            //     {
            //         try
            //         {
            //             // 读取JSON文件
            //             var json = System.IO.File.ReadAllText(openDialog.FileName);
            //             var projectData = Newtonsoft.Json.JsonConvert.DeserializeObject<ProjectData>(json);
                        
            //             // 清空当前树视图和组件数据
            //             TreeWinformList.Nodes.Clear();
            //             _treeData = new WinformTreeDatastruct();
                        
            //             // 重建窗口和组件
            //             foreach (var windowData in projectData.Windows)
            //             {
            //                 // 创建窗口节点
            //                 var windowNode = _treeData.AddWindow(windowData.Name, new Size(800, 600));
                            
            //                 // 重建组件
            //                 foreach (var componentData in windowData.Components)
            //                 {
            //                     var component = _componentList.CreateComponent(componentData.Type);
            //                     if (component != null)
            //                     {
            //                         component.Position = componentData.Position;
                                    
            //                         // 设置组件属性
            //                         if (componentData.Properties != null)
            //                         {
            //                             foreach (var prop in componentData.Properties)
            //                             {
            //                                 var property = component.GetType().GetProperty(prop.Key);
            //                                 if (property != null && property.CanWrite)
            //                                 {
            //                                    if (property.PropertyType == typeof(Color))
            //                                     {
            //                                         // 处理Color类型的特殊转换
            //                                         property.SetValue(component, Color.FromArgb(Convert.ToInt32(prop.Value)));
            //                                     }
            //                                     else if (property.PropertyType == typeof(Font))
            //                                     {
            //                                         // 处理Font类型的特殊转换
            //                                         var fontConverter = new FontConverter();
            //                                         property.SetValue(component, fontConverter.ConvertFromString(prop.Value.ToString()));
            //                                     }
            //                                     else if (property.PropertyType == typeof(FlashInterval))
            //                                     {
            //                                         // 处理FlashInterval类型的特殊转换
            //                                         property.SetValue(component, (FlashInterval)Convert.ToInt32(prop.Value));
            //                                     }
            //                                      else if (property.PropertyType == typeof(DateFormat))
            //                                     {
            //                                         // 处理DateFormat类型的特殊转换
            //                                         property.SetValue(component, (DateFormat)Convert.ToInt32(prop.Value));
            //                                     }
            //                                     else if (property.PropertyType == typeof(TimeFormat))
            //                                     {
            //                                         // 处理TimeFormat类型的特殊转换
            //                                         property.SetValue(component, (TimeFormat)Convert.ToInt32(prop.Value));
            //                                     }
            //                                     else if (property.PropertyType == typeof(DeviceType))
            //                                     {
            //                                         // 处理DeviceType类型的特殊转换
            //                                         property.SetValue(component, (DeviceType)Convert.ToInt32(prop.Value));
            //                                     }
            //                                     else
            //                                     {
            //                                         property.SetValue(component, prop.Value);
            //                                     }
            //                                 }
            //                             } 
            //                         }
                                    
            //                         // 添加到窗口
            //                         _treeData.AddComponentToWindow(windowData.Id, component);
            //                     }
            //                 }
            //             }
                        
            //             // 重新绑定树视图
            //             _treeData.BindToTreeView(TreeWinformList);
                        
            //              //这里自动选择第0号窗口
            //             if (TreeWinformList.Nodes.Count > 0)
            //             {
            //                 TreeWinformList.SelectedNode = TreeWinformList.Nodes[0];
            //             }
            //             //MessageBox.Show("项目载入成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //         }
            //         catch (Exception ex)
            //         {
            //             MessageBox.Show($"载入项目失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //         }
            //     }
            // }
        
        }
    }
}
